package com.zhc.dejingapi.utils.process;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhc.dejingapi.entity.*;
import com.zhc.dejingapi.entity.vo.QingeqAndRealtimeVo;
import com.zhc.dejingapi.mapper.*;
import com.zhc.dejingapi.pojo.qingflow.QingflowApiInfo;
import com.zhc.dejingapi.pojo.qingflow.appdata.adddata.QingAddDataResultMain;
import com.zhc.dejingapi.pojo.qingflow.queryresult.QingQueryActionResultBase;
import com.zhc.dejingapi.service.RealtimeService;
import com.zhc.dejingapi.utils.qing.QingflowAPIUtils;
import com.zhc.dejingapi.utils.qing.UploadUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zhc
 * @date 2024年07月27日 13:27
 */
@Configuration
public class ProcessUtils {
    @Resource
    private RealtimeService realtimeService;

    @Resource
    private QingEquipmentMapper qingEquipmentMapper;

    @Resource
    private WmMapper wmMapper;

    @Resource
    private SpcMapper spcMapper;

    @Resource
    private QingMoordermainMapper qingMoordermainMapper;

    @Resource
    private QingSfcmoroutingshiftMapper qingSfcmoroutingshiftMapper;

    @Resource
    private UploadUtils uploadUtils;

    @Resource
    private QingflowApiInfo qingflowApiInfo;

    @Resource(name = "redisTemplateLinux")
    private RedisTemplate<String,Object> redisTemplateLinux;

    public void checkAD() throws Exception {
//        List<RealtimeEntity> listRealtime = realtimeService.list();
//
//        for (RealtimeEntity r : listRealtime) {
//            Date abnormalDowntime = r.getAbnormalDowntime();
//            Date lastSpcTime = r.getLastSpcTime();
//
//            Date dateNow= DateUtil.date();
//            if(abnormalDowntime!=null){
//                long between = DateUtil.between(abnormalDowntime, dateNow, DateUnit.SECOND);
//                if(between>=180&&r.getAddStatus()==1){
//                    System.out.println("异常超时");
//                    QueryWrapper<WmEntity> wmEntityQueryWrapper = new QueryWrapper<>();
//                    wmEntityQueryWrapper.eq("e_id",r.getEId()).eq("wmTime",r.getAbnormalDowntime());
//                    WmEntity wmEntity = wmMapper.selectOne(wmEntityQueryWrapper);
//                    uploadUtils.addAbnormal("7tmv1ke01o01",r.getEId(),wmEntity.getWmMsg(), LocalDateTimeUtil.format(wmEntity.getWmTime(), DatePattern.NORM_DATETIME_PATTERN));
//                }
//            }else if(lastSpcTime!=null){
//                long between = DateUtil.between(lastSpcTime, dateNow, DateUnit.SECOND);
//                QueryWrapper<QingMoordermainEntity> q = new QueryWrapper<>();
//                q.eq("eqCode",r.getEId());
//                q.eq("moStatus","生产中");
//                Long l = qingMoordermainMapper.selectCount(q);
//                if(between>300&&r.getAddStatus()==0&&l>0){
//                    System.out.println("停机超时");
//                    uploadUtils.addStop("7svoq52c1o01",r.getEId(), DateUtil.formatDateTime(r.getLastSpcTime()));
//                }
//            }
//        }

        List<QingEquipmentEntity> listEq = qingEquipmentMapper.getEqList();
        for (QingEquipmentEntity eq : listEq) {
            Long eId = eq.getMainId();
            String keySpc=eId+"_lastSpcTime";
            String keyAbnormal=eId+"_abnormalDowntime";
            Date abnormalDowntime;
            Date lastSpcTime;
            Date dateNow= DateUtil.date();
            if(Boolean.TRUE.equals(redisTemplateLinux.hasKey(keyAbnormal))){
                abnormalDowntime = new Date((Long)redisTemplateLinux.opsForValue().get(keyAbnormal));
                long between = DateUtil.between(abnormalDowntime, dateNow, DateUnit.SECOND);
                //System.out.println(between);
                if(between>=180){
                    //System.out.println("异常超时");
                    QueryWrapper<WmEntity> wmEntityQueryWrapper = new QueryWrapper<>();
                    wmEntityQueryWrapper.eq("e_id",eId).eq("wmTime",abnormalDowntime);
                    WmEntity wmEntity = wmMapper.selectOne(wmEntityQueryWrapper);
                    uploadUtils.addAbnormal("7tmv1ke01o01",eId,wmEntity.getWmMsg(), LocalDateTimeUtil.format(wmEntity.getWmTime(), DatePattern.NORM_DATETIME_PATTERN),keyAbnormal);
                }
            }else{
                System.out.println(keyAbnormal+"不存在");
            }
            if(Boolean.TRUE.equals(redisTemplateLinux.hasKey(keySpc))){
                lastSpcTime = new Date((Long)redisTemplateLinux.opsForValue().get(keySpc));
                long between = DateUtil.between(lastSpcTime, dateNow, DateUnit.SECOND);
                QueryWrapper<QingMoordermainEntity> q = new QueryWrapper<>();
                q.eq("eqCode",eId);
                q.eq("moStatus","生产中");
                Long l = qingMoordermainMapper.selectCount(q);
                //System.out.println(between);
                if(between>300&&l>0){
                    //System.out.println("停机超时");
                    //System.out.println(eId);
                    //System.out.println(DateUtil.formatDateTime(lastSpcTime));
                    uploadUtils.addStop("7svoq52c1o01",eId, DateUtil.formatDateTime(lastSpcTime),keySpc);
                }
            }else{
                System.out.println(keySpc+"不存在");
            }
        }
    }

    public void addEqNum() throws Exception {
        List<QingeqAndRealtimeVo> eqAndRealtimeList = qingEquipmentMapper.getEqAndRealtime();
        Date now = DateUtil.date();
        LocalDateTime localDateTime = LocalDateTimeUtil.of(now);
        List<String> opNameList= Arrays.asList("注塑","二次注塑","注塑手动摸");
        for (QingeqAndRealtimeVo eqAndRealtime : eqAndRealtimeList){
            Long mainId = eqAndRealtime.getMainId();
            QingEquipmentEntity qingEquipmentEntity = new QingEquipmentEntity();
            qingEquipmentEntity.setClampingUpdateTime(localDateTime);
            qingEquipmentEntity.setMainId(mainId);
            LocalDateTime clampingUpdateTime = eqAndRealtime.getClampingUpdateTime();//最后一次上传时间
            if(clampingUpdateTime!=null){
                QueryWrapper<SpcEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("e_id",mainId);
                QueryWrapper<QingSfcmoroutingshiftEntity> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("eqCode",eqAndRealtime.getEqCode()).eq("workTaskState","已启动").in("opName",opNameList);
                List<QingSfcmoroutingshiftEntity> qingSfcmoroutingshiftEntities = qingSfcmoroutingshiftMapper.selectList(queryWrapper1);
                if(qingSfcmoroutingshiftEntities.size()>0){
                    for (int i=0; i<qingSfcmoroutingshiftEntities.size(); i++) {
                        Integer gatherCloseNum = qingSfcmoroutingshiftEntities.get(i).getGatherCloseNum();//采集合模数（乘穴数）
                        Integer openAndCloseNum = qingSfcmoroutingshiftEntities.get(i).getOpenAndCloseNum();//开合模次数
                        Integer moldAvailCavityQty = qingSfcmoroutingshiftEntities.get(i).getMoldAvailCavityQty();//实际穴数
                        LocalDateTime actualStartTime = qingSfcmoroutingshiftEntities.get(i).getActualStartTime();//实际开始时间
                        LocalDateTime actualEndTime = qingSfcmoroutingshiftEntities.get(i).getActualEndTime();//实际结束时间
                        Integer newGatherCloseNum=0;
                        Integer newOpenAndCloseNum=0;
                        Long l=0L;
                        if(clampingUpdateTime.isBefore(actualStartTime)){
                            queryWrapper.between("time",actualStartTime,localDateTime);
                            l = spcMapper.selectCount(queryWrapper);
                        }else if(actualEndTime!=null&&localDateTime.isAfter(actualEndTime)){
                            queryWrapper.between("time",clampingUpdateTime,actualEndTime);
                            l = spcMapper.selectCount(queryWrapper);
                        }else if(clampingUpdateTime.isAfter(actualStartTime)||clampingUpdateTime.isEqual(actualStartTime)){
                            queryWrapper.between("time",clampingUpdateTime,localDateTime);
                            l = spcMapper.selectCount(queryWrapper);
                        }
                        if(gatherCloseNum==null){
                            gatherCloseNum=0;
                        }
                        if(openAndCloseNum == null){
                            openAndCloseNum=0;
                        }
                        if(moldAvailCavityQty==null){
                            moldAvailCavityQty=1;
                        }
                        newGatherCloseNum = Math.toIntExact(gatherCloseNum + l * moldAvailCavityQty);
                        newOpenAndCloseNum = Math.toIntExact(openAndCloseNum + l);
                        Map<String,Object> map = new HashMap<>();
                        map.put("qingApplyId",qingSfcmoroutingshiftEntities.get(i).getQingApplyId());
                        map.put("newOpenAndCloseNum",newOpenAndCloseNum);
                        map.put("newGatherCloseNum",newGatherCloseNum);
                        String jsonStr = JSONUtil.toJsonStr(map);
                        QingAddDataResultMain qingAddDataResultMain = QingflowAPIUtils.UpdDataToQingByQSource(qingflowApiInfo, "f5efc900-0c81-49ab-a5f5-4c2439e94450", jsonStr);
                        if(qingAddDataResultMain.getErrCode()==0){
                            String requestId = qingAddDataResultMain.getResult().getRequestId();
                            String newRequestId = requestId.replace(" ", "%20");
                            QingQueryActionResultBase qingQueryActionResultBase = QingflowAPIUtils.GetRequestResult(qingflowApiInfo, newRequestId);
                            if(qingQueryActionResultBase.getErrorCode()==0){
                               i++;
                            }
                        }

                    }
                    qingEquipmentMapper.updateById(qingEquipmentEntity);
                }
            }

        }
    }
}
